<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/7/15 17:10
 */

namespace App\Service\System;


use App\Exception\ServiceException;
use Hyperf\HttpServer\Contract\RequestInterface;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use function Hyperf\Config\config;

class UploadOssQiNiuService
{

    protected $auth;

    public function __construct()
    {
        $this->auth = new Auth(config('oss.qi_niu.ak'),config('oss.qi_niu.sk'));
    }

    /**
     * 上传附件
     * @param RequestInterface $request
     * @return mixed
     * @throws \Exception
     */
    public function uploadFile(RequestInterface $request)
    {
        if (!$request->hasFile('file')) {
            throw new ServiceException("附件不存在");
        }
        $file = $request->file('file');
        $dirPath = 'yjz'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.date("Ym/d");

        $token = $this->auth->uploadToken(config('oss.qi_niu.bucket_name'));
        $savePath = $dirPath.DIRECTORY_SEPARATOR.$file->getClientFilename();
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token,$savePath,$file->getRealPath(), null, 'application/octet-stream', true, null, 'v2');
        if ($err !== null) {
            throw new ServiceException("上传失败:{$err}");
        }
        return config('oss.base_path').$ret['key'];
    }


    /**
     * 上传base64编码的图片
     * @param string $base64Image base64编码的图片数据
     * @param string $fileName 文件名
     * @return string
     * @throws \Exception
     */
    public function uploadBase64Image(string $base64Image, string $fileName = ''): string
    {
        // 检查是否为有效的base64图片数据
        if (empty($base64Image)) {
            throw new ServiceException("图片数据不能为空");
        }

        // 匹配base64数据格式，提取图片数据
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64Image, $result)) {
            $imageData = substr($base64Image, strlen($result[1]));
            $fileExt = $result[2];
        } else {
            $imageData = $base64Image;
            // 默认使用jpg格式
            $fileExt = 'png';
        }

        // 解码base64数据
        $imageBinary = base64_decode($imageData);
        if ($imageBinary === false) {
            throw new ServiceException("无效的base64图片数据");
        }

        // 生成文件名
        if (empty($fileName)) {
            $fileName = uniqid() . '.' . $fileExt;
        } elseif (strpos($fileName, '.') === false) {
            $fileName .= '.' . $fileExt;
        }

        // 构建保存路径
        $dirPath = 'yjz' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . date("Ym/d");
        $savePath = $dirPath . DIRECTORY_SEPARATOR . $fileName;

        // 获取上传token
        $token = $this->auth->uploadToken(config('oss.qi_niu.bucket_name'));

        // 上传管理器
        $uploadMgr = new UploadManager();

        // 上传二进制数据
        list($ret, $err) = $uploadMgr->put(
            $token,
            $savePath,
            $imageBinary,
            null,
            'application/octet-stream',
            true,
            null,
            'v2'
        );

        if ($err !== null) {
            throw new ServiceException("上传失败:{$err}");
        }

        return config('oss.base_path') . $ret['key'];
    }

}